package com.kaifamiao.wendao.service;

import com.kaifamiao.wendao.dao.CustomerDao;
import com.kaifamiao.wendao.dao.ExplainDao;
import com.kaifamiao.wendao.dao.FileInfoDao;
import com.kaifamiao.wendao.dao.TopicDao;
import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.utils.SnowflakeIdGenerator;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

public class CustomerService {

    private CustomerDao customerDao = new CustomerDao();
    private ExplainDao explainDao = new ExplainDao();
    private TopicDao topicDao = new TopicDao();
    private FileInfoDao f = new FileInfoDao();
    private SnowflakeIdGenerator idGenerator = SnowflakeIdGenerator.getInstance();

    public String encrypt(final String source,String salt){
        //首先对原始密码进行加密
        String encrypted = DigestUtils.sha1Hex(source);
        StringBuilder builder = new StringBuilder(encrypted);
        //在加密后的字符序列指定位置插入盐值
        builder.insert(20,salt);
        //获得插入后的盐值
        String inserted =builder.toString();
        //对插入盐值后的字符串进行加密
        return DigestUtils.sha1Hex(inserted);
    }

    public boolean save(Customer c){
        if(c == null) {
            return false;
        }
        // 采用雪花算法生成对象标识符并设置到Customer实例中
        c.setId(idGenerator.generate());
        // 随机生成盐值并设置到Customer实例中
        c.setSalt(RandomStringUtils.randomAlphanumeric(5));
        // 对原始密码加密后重新设置到Customer实例中
        c.setPassword(encrypt(c.getPassword(),c.getSalt()));
        // 以当前时间为注册日期
        c.setRegisterDate(LocalDate.now());
        return customerDao.save(c);
    }

    public Customer load(Long id){
        return customerDao.find(id);
    }

    public boolean load(String username){
        return customerDao.find(username);
    }

    public Customer loadName(String username){
        return customerDao.findName(username);
    }


    public List<Customer> loadAll(){
        return customerDao.findAll();
    }

    public boolean update(Customer c){
        return customerDao.update(c);
    }

    public boolean remove(Long id){
        return customerDao.remove(id);
    }

    public boolean removeCustomer(Long id){
        return this.c(id)?customerDao.remove(id):false;
    }
    //删除用户
    public boolean a(Long id){
        return f.remove(id)?explainDao.teremove(id) :false;
    }
    //删除所有话题
    public boolean b(Long id){
        return this.a(id)?topicDao.tremove(id):false;
    }
    //删除话题后删除所有解答
    public boolean c(Long id){
        return  this.b(id)?explainDao.eremove(id):false;
    }
}
